export function loadMore(element: any, callback: any) {
  function _loadMore() {
    let clientHeight = element.clientHeight
    let scrollTop = element.scrollTop
    let scrollHeight = element.scrollHeight
    if (clientHeight + scrollTop + 10 >= scrollHeight) {
      callback()
    }
  }
  element.addEventListener('scroll', debounce(_loadMore, 300))
}

export function downRefresh(element: HTMLDivElement, callback: Function) {
  let startY: number
  let distance: number
  let originalTop = element.offsetTop
  let startTop: number
  let $timer: any = null
  element.addEventListener('touchstart', function (event: TouchEvent) {
    if ($timer) clearInterval($timer)
    let touchMove = throttle(_touchMove, 30)
    if (element.scrollTop === 0) {
      startTop = element.offsetTop
      startY = event.touches[0].pageY
      element.addEventListener('touchmove', touchMove)
      element.addEventListener('touchend', touchEnd)
    }

    function _touchMove(event: TouchEvent) {
      let pageY = event.touches[0].pageY
      if (pageY > startY) {
        distance = pageY - startY
        element.style.top = startTop + distance + 'px'
      } else {
        element.removeEventListener('touchmove', touchMove)
        element.removeEventListener('touchend', touchEnd)
        if (distance > 30) {
          callback()
        }
        $timer = setInterval(() => {
          let currentTop = element.offsetTop
          if (currentTop - originalTop > 1) {
            element.style.top = currentTop - 1 + 'px'
          } else {
            element.style.top = originalTop + 'px'
          }
        }, 13)
      }
    }
    function touchEnd(_event: TouchEvent) {
      element.removeEventListener('touchmove', touchMove)
      element.removeEventListener('touchend', touchEnd)
      if (distance > 30) {
        callback()
      }
      $timer = setInterval(() => {
        let currentTop = element.offsetTop
        if (currentTop - originalTop > 1) {
          element.style.top = currentTop - 1 + 'px'
        } else {
          element.style.top = originalTop + 'px'
        }
      }, 13)
    }
  })
}

export function debounce(fn: any, wait: number) {
  var timeout: any = null
  return function () {
    if (timeout !== null) clearTimeout(timeout)
    timeout = setTimeout(fn, wait)
  }
}

export function throttle(fn: any, delay: number) {
  var prev = Date.now()
  return function () {
    var context = this
    var args = arguments
    var now = Date.now()
    if (now - prev >= delay) {
      fn.apply(context, args)
      prev = Date.now()
    }
  }
}

export const store = {
  set(key: string, val: string) {
    sessionStorage.setItem(key, val)
  },
  get(key: string) {
    return sessionStorage.getItem(key)
  },
}
export function getNumber(str: string) {
  return parseFloat(str.slice(1, str.length - 1))
}
